package com.jzo2o.customer.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.jzo2o.api.publics.SmsCodeApi;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.common.enums.SmsBussinessTypeEnum;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.dto.request.InstitutionRegisterReqDTO;
import com.jzo2o.customer.service.IRegisterService;
import com.jzo2o.customer.service.IServeProviderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Description IRegisterServiceImpl
 * @Author jzh
 * @Date 2025-08-06  15:42
 */
@Service
public class RegisterServiceImpl implements IRegisterService {

    @Resource
    private SmsCodeApi smsCodeApi;

    @Resource
    private IServeProviderService serveProviderService;

    /**
     * 机构注册接口
     * @param institutionRegisterReqDTO
     */
    @Override
    public void register(InstitutionRegisterReqDTO institutionRegisterReqDTO) {
        // 数据校验
        if(StringUtils.isEmpty(institutionRegisterReqDTO.getVerifyCode())){
            throw new BadRequestException("验证码错误，请重新获取");
        }

        // 远程调用publics服务校验验证码是否正确
        Boolean isSuccess = smsCodeApi.verify(institutionRegisterReqDTO.getPhone(), SmsBussinessTypeEnum.INSTITION_REGISTER, institutionRegisterReqDTO.getVerifyCode()).getIsSuccess();
        if(!isSuccess) {
            throw new BadRequestException("验证码错误，请重新获取");
        }

        // 根据手机号和用户类型获取机构信息
        ServeProvider serveProvider = serveProviderService.findByPhoneAndType(institutionRegisterReqDTO.getPhone(), UserType.INSTITUTION);
        // 判断机号是否已注册
        if(ObjectUtil.isNotEmpty(serveProvider)) {
            throw new BadRequestException("该手机号已注册");
        }
        // 进行注册
        serveProviderService.add(institutionRegisterReqDTO.getPhone(), UserType.INSTITUTION, institutionRegisterReqDTO.getPassword());

    }
}
